import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import React, { useState, useEffect } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";

function MyEditor({ defaultHtml, updateHtml, is }: any) {
	const [editor, setEditor] = useState<any>(null); // 存储 editor 实例
	const [html, setHtml] = useState(defaultHtml); // 编辑器内容

	useEffect(() => {
		updateHtml(html);
	}, [html]);

	const toolbarConfig = {};
	const editorConfig = {
		placeholder: "请输入内容...",
		readOnly: is
	};

	// 及时销毁 editor ，重要！
	useEffect(() => {
		return () => {
			if (editor == null) return;
			editor?.destroy();
			setEditor(null);
		};
	}, [editor]);

	return (
		<>
			<div style={{ zIndex: 100, height: "500px", padding: "1vh 0", width: "700px", margin: "0 auto" }}>
				<Toolbar
					editor={editor}
					defaultConfig={toolbarConfig}
					mode="default"
					style={{ borderBottom: "1px solid #ccc", display: is ? "none" : "" }}
				/>
				<Editor
					defaultConfig={editorConfig}
					value={is ? defaultHtml : html}
					onCreated={setEditor}
					onChange={editor => setHtml(editor.getHtml())}
					mode="default"
					style={{ height: "80%", "overflow-y": "hidden" }}
				/>
			</div>
		</>
	);
}

export default MyEditor;
